#!/usr/bin/env ruby

require 'rubygems'
require 'activeresource'

class User < ActiveResource::Base
 self.site = "http://localhost:3000"
end

#list all users
def list_users
  puts "listing all users.."
  users = User.find(:all)
  users.each do |user|
    puts "#{user.id}, #{user.username}, #{user.email}"
  end
end

#create a user. return userid
def create_user(username, password, email)
  puts "creating user: #{username}, #{password}, #{email}.."
  user = User.new(:username=>username, :password=>password, :email=>email)

  if user.save
    puts "user #{user.username} created! user id: #{user.id}"
    return user.id
  else
    puts "error creating user #{user.username}: #{user.errors.full_messages.to_sentence}"
  end
end

# update user with new name, password, email
def update_user(id, username, password, email)
  puts "updatig user.."
  user =  User.find(id)

  user.username = username;
  user.password = password;
  user.email = email;

  if user.save
    puts "user #{user.username} updated!"
    return user.id
  else
    puts "error updating user: #{user.errors.full_messages.to_sentence}"
  end

end


# get user by the user id
def find_user(id)
  puts "looking for user.."
  user =  User.find(id)

  puts "found user: #{user.username}, #{user.email}"

  rescue
    puts "error occured trying to find a user with userid: #{id}"
end

# delete user by the user id
def delete_user(id)
  puts "destroing user.."
  user = User.find(id).destroy

  puts "user with the id: #{id} destroyed"

  rescue
    puts "error occured trying to find a user with userid: #{id}"
end


puts "-----------------------------------------------"
puts "Test for RESTful API"
puts "Basic CRUD operations for User"
puts "-----------------------------------------------"

list_users

puts "-----------------------------------------------"

id1 = create_user('andrey', 'andrey', 'andrey@mail.com')
id2 = create_user('kateryna', 'kateryna', 'kateryna@mail.com')
id3 = create_user('kuldip', 'kuldip', 'kuldip@mail.com')

puts "-----------------------------------------------"

find_user(id1)
find_user(id2)
find_user(id3)

puts "-----------------------------------------------"

update_user(id1, 'Andrey Gusev', 'secret', 'andrey@email.com')

puts "-----------------------------------------------"

list_users

puts "-----------------------------------------------"

delete_user(id1)
delete_user(id2)
delete_user(id3)
